package com.kedll.library.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import com.kedll.library.R;


/**
 * Created by css on 2016/8/24.
 */
public class UnitEditText extends android.support.v7.widget.AppCompatEditText implements View.OnFocusChangeListener {
    private String unit;

    public UnitEditText(Context context) {
        this(context, null);
    }

    public UnitEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.UnitEditText);
        unit = a.getString(R.styleable.UnitEditText_unit);
        a.recycle();

        setOnFocusChangeListener(this);
    }

    public UnitEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            //TODO 隱藏單位
            String tmpStr = getText().toString();
            setText(tmpStr.replace(unit, ""));
        } else {
            //TODO 顯示單位
            String tmpStr = getText().toString();
            if (tmpStr.length() > 0) {
                setText(String.format("%s%s", tmpStr, unit));
            }
        }
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }

}
